package com.lib.utls.live;


import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.bean.ToLiveBeanBase;
import com.lib.bean.WanPeiConfigBean;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.db.shared_prefrences.interfaces.UserCacheInterface;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.utls.pop.LiveCheckMoneyPopupUtils;
import com.luck.picture.lib.tools.ToastManage;

import java.util.List;


/**
 * 对进入直播的流程进行一次封装方便多次调用
 */
public class ToClassUtils {


    private WanPeiConfigBean.ObjBean wanPeiObjBean;

    private Activity activity;

    public ToClassUtils(Activity activity) {

        this.activity = activity;


    }

    private static ToClassUtils instance;

    public static synchronized ToClassUtils getInstance(Activity activity) {

        if (instance == null) {
            instance = new ToClassUtils(activity);
        }
        return instance;
    }


    /**
     * 去上课
     *
     * @param course_type
     * @param course_id
     */
    public void goToClass(final String course_type, final String course_id) {

        //保存课程的类型以及该课程的Id，用于RoomControlFragment分享
        final UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(activity).getUserCache();
        userCacheInterface.setBussessType(course_type);
        userCacheInterface.setCourseId(course_id);

        getWanPeiConfig();//获取晚陪课公共配置

//        PermissionUtil.getInstance(activity).externalZhiBo(new PermissionUtil.RequestPermission() {
//            @Override
//            public void onRequestPermissionSuccess() {

        //type:0晚陪课，1一对一，2班级课，3体验课
        //支付了去上课
        HttpUtils.with(activity)
                .addParam("requestType", "TO_CLASS")
                .addParam("course_type", course_type)
                .addParam("course_id", course_id)
                .addParam("token", userCacheInterface.getUserToken())
                .execute(new HttpDialogCallBack<ToLiveBeanBase>() {
                    @Override
                    public void onSuccess(final ToLiveBeanBase result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            String identity = userCacheInterface.getUserIdentity();

                            if (identity.equals("1")) {

                                toClass(result);

                            } else {

                                if (course_type.equals("0")) {

//                                            toClass(result);
                                    //只有晚陪课有
                                    toClassPop(result);


                                } else {

                                    toClass(result);

                                }

                            }

                        } else {


                            showToast(result.getMsg());


                        }

                    }

                    @Override
                    public void onError(String e) {

                    }


                });


//            }
//
//            @Override
//            public void onRequestPermissionFailure() {
//                LogUtil.e("权限请求失败");
//            }
//
//        });
    }

    private void toClassPop(final ToLiveBeanBase result) {

        final LiveCheckMoneyPopupUtils liveCheckMoneyPopupUtils = new LiveCheckMoneyPopupUtils(activity);
        liveCheckMoneyPopupUtils.setLiveCheckMoneyPopupUtilsListener(new LiveCheckMoneyPopupUtils.LiveCheckMoneyPopupUtilsListener() {
            @Override
            public void onCancle() {

            }

            @Override
            public void onSure() {

                if (!"".equals(wanPeiObjBean.getAccount()) && !"".equals(wanPeiObjBean.getLive_billing())) {
                    Double account = Double.parseDouble(wanPeiObjBean.getAccount());
                    Double live_billing = Double.parseDouble(wanPeiObjBean.getLive_billing());

                    if (account >= live_billing) {

                        toClass(result);

                    } else {

                        ToastManage.s(activity, "您的兔币不足，请先去充值");
                        return;

                    }

                }

            }
        });

        final String rule = "计费方式:每" + wanPeiObjBean.getLive_billing_time()
                + "分钟消费" + wanPeiObjBean.getLive_billing() + "兔币";

        final String money = "当前兔币:" + wanPeiObjBean.getAccount();

        if (!activity.isFinishing()) {
            liveCheckMoneyPopupUtils.showAnswerPopuPopu(activity.getWindow().getDecorView(), rule, money);
        }

    }

    public void toClass(ToLiveBeanBase result) {
        String roomToken = result.getObj().getRoomtoken();
        String teacherPhone = result.getObj().getPhoen();
        ARouter.getInstance().build(ARouterPathUtils.Live_MainRoomActivity)
                .withString("roomToken", roomToken)
                .withString("teacherPhone", teacherPhone)
                .withString("roomName", result.getObj().getRoomname())
                .withString("userPhone", SharedPreferenceManager.getInstance(activity).getUserCache().getUserPhone())
                .withString("uuid", result.getObj().getUuid())
                .withString("whitetoken", result.getObj().getWhitetoken())
                .navigation();
    }


    private void getWanPeiConfig() {

        HttpUtils.with(activity)
                .addParam("requestType", "LIVE_EC_CONFIG")
                .addParam("token", SharedPreferenceManager.getInstance(activity).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<WanPeiConfigBean>() {
                    @Override
                    public void onSuccess(WanPeiConfigBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            if (result.getObj() != null) {

                                wanPeiObjBean = result.getObj();

                            }

                        }

                    }

                    @Override
                    public void onError(String e) {

                    }
                });


    }

    /**
     * Toast
     *
     * @param text
     */

    private Toast mToast;

    public void showToast(String text) {
        if (!TextUtils.isEmpty(text)) {
            if (mToast == null) {
                mToast = Toast.makeText(activity, "", Toast.LENGTH_SHORT);
            }
            mToast.setText(text);
            mToast.show();
        }
    }


    /**
     * 判断某个activity是否在前台显示
     */
    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    /**
     * 判断某个界面是否在前台,返回true，为显示,否则不是
     */
    public static boolean isForeground(Activity context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;

    }


}
